<template>
	<view class="content">
		<view class="container">
			<view v-if="current == 1" class="marchrt_box">
				<view v-if="marchrtList.length > 0">
					<view class="marchrt" v-for="(item, index) in marchrtList" :key="index" @click="_changeMarchrt(item)">
						<custom-card>
							<view class="marchrt_main">
								<view class="marchrt_header">
									<image class="marchrt_header_img" @load="imgLoad" @error="imgError" :src="item.icon?item.icon:''" mode="aspectFit"></image>
								</view>
								<view class="marchrt_content">
									<view class="marchrt_name">
										{{item.merchantName}}
									</view>
									<view class="marchrt_remark">
										{{item.remark==''?'暂无描述':item.remark}}
									</view>
									<view class="marchrt_start_and">
										营业时间: {{item.openingTime}} 至 {{item.closingTime}}
									</view>
								</view>
							</view>
						</custom-card>
					</view>
				</view>
				<view class="no_data" v-else>
					<no-content noContent='暂无商家供应餐食!'/>
				</view>
			</view>
			<view v-else-if="current == 2" class="my_meal">
				<view class="tab_my_meal">
					<custom-tabs :tabs="myMeal" @change="tabChange"></custom-tabs>
				</view>
				<view class="my_meal_list" v-if="mealList.length > 0">
					<view class="supply_item" v-for="(item, index) in mealList" :key="index"> <!-- @click="jumpToDetail(item)" -->
						<custom-card>
							<view class="supply_header">
								<view class="supply_type">
									<text>{{item.merchantName}}</text>
								</view>
								<view class="supply_result appling">
									<text>{{statusToType(item.status)}}</text>
								</view>
							</view>
							<view class="supply_description">
								预定餐次：{{item.reservationDate}} {{item.mealTimesName}} 
							</view>
							<view class="supply_menus">
								<view class="menu_item">
									<text>定金：</text>
									<text>￥{{item.amount.toFixed(2)}}</text>
								</view>
								<view class="menu_item">
									<text>下单时间：</text>
									<text>{{item.modifyTime}}</text>
								</view>
							</view>
							<view class="supply_price">
								<view>
									结算金额：<text class="hint">￥{{item.settleAmount == null ? 0 : item.settleAmount.toFixed(2)}}</text>元
								</view>
								<view class="status_btn_box">
									<view v-if="item.status == 10 && item.orderIsCanCancel == 1" class="book_btn" @click="confirmOrder(item)">
										确认
									</view>
									<view v-if="(item.status == 20 || item.status == 21) && item.orderIsCanCancel == 1" class="book_btn" @click="cancelOrderHandle(item)">
										退订
									</view>
									<view v-if="item.status == 10 || item.status == 20 || item.status == 30 || item.status == 40" class="book_btn" @click="confirmOrder(item)">
										详情
									</view>
								</view>
							</view>
						</custom-card>
					</view>
				</view>
				<view class="no_data" v-else>
					<no-content noContent='暂无相关订单'/>
				</view>
			</view>
			<view v-else-if="current == 3" class="meal_qrcode">
				<view v-if="canUseList.length > 0">
					<view class="supply_item" v-for="(item, index) in canUseList" :key="index">
						<custom-card>
							<view class="supply_header">
								<view class="supply_type">
									<text>{{item.merchantName}} {{item.mealTimesName}} </text>
								</view>
							<view class="supply_result appling">
								<text>{{item.reservationDate}}</text>
							</view>
							</view>
							<view class="supply_menus">
								<view class="menu_item">
									<text>定金：</text>
									<text>￥{{item.amount.toFixed(2)}}</text>
								</view>
								<view class="menu_item">
									<text>下单时间：</text>
									<text>{{item.modifyTime}}</text>
								</view>
							</view>
							<view class="show_qrcode" @click="showQrcode(item)">
								<text>查看二维码</text>
							</view>
						</custom-card>
					</view>
				</view>
				<view class="no_data" v-else>
					<no-content noContent='暂无可消费二维码数据'/>
				</view>
			</view>
		</view>
		<view class="tab_meal">
			<view class="tab_item" :class="{'current': current == item.index}" v-for="(item,index) in tabMeal" :key='index'
			 @click="mealHandle(item)">{{item.title}}</view>
		</view>
		<view class="org_change">
			<!-- <view class="org_name">{{userList[orgCurrent].orgName?userList[orgCurrent].orgName:'未绑定人员信息'}}</view> -->
			<!-- <view class="org_name"></view> -->
			<!-- <picker @change="_SchoolsChange" :value="orgCurrent" :range="userList" range-key="orgName"> -->
				<view class="change_btn" @click="showOrg = true">
					<image class="change_icon" src="/static/images/change.png" mode="scaleToFill"></image>
					<text>切换用户</text>
				</view>
			<!-- </picker> -->
		</view>
		<view class="qr_code_box" v-if="openQrcode">
			<view class="mask" @click="hideQrcode"></view>
			<view class="qr_code_bg">
				<view class="close_icon" @click="hideQrcode">×</view>
				<view class="qr_code_merchant">
					商家： {{qrcodeMsg.merchantName}}
				</view>
				<tki-qrcode cid="qrcode" :showLoading="true" loadingText="用餐码生成中" icon="/static/images/home/login.png" ref="qrcode" :val="qrcode" :size="300" :onval="true" :loadMake="true" :usingComponents="true"/>
				<view class="qr_code_msg">
					<view class="msg_item">
						<text class="msg_title">预约餐次:</text>
						<text class="msg_content">{{qrcodeMsg.reservationDate}} {{qrcodeMsg.mealTimesName}}</text>
					</view>
					<view class="msg_item">
						<text class="msg_title">预约码:</text>
						<text class="msg_content">{{qrcodeMsg.takeNo}}</text>
					</view>
					<view class="msg_item">
						<text class="msg_title">预约定金:</text>
						<text class="msg_content">{{Number(qrcodeMsg.amount).toFixed(2)}} 元</text>
					</view>
					<view class="msg_item">
						<text class="msg_title">预约总份数:</text>
						<text class="msg_content">{{qrcodeMsg.quantity}}份</text>
					</view>
					<view class="msg_item">
						<text class="msg_title">剩余可取份数:</text>
						<text class="msg_content">{{qrcodeMsg.quantity - qrcodeMsg.takeQuantity}}份</text>
					</view>
				</view>
			</view>
		</view>
		<mc-modal :isShow="showMcModal" :content="content" :showCancel="showCancel"
        @ok="ok" @cancel="showMcModal = false" :title="title"></mc-modal>
		<custom-popup v-model="showOrg" :ranges="ranges" @change="_SchoolsChange" @confirm="_confirmStudent"/>
	</view>
</template>

<script>
	let _this;
	import {
		getMerchantList,
		findMealOrderPage,
		findMealOrder,
		queryStudentCardBalance,
		cancelMealOrder,
		orderToInvisible,
		updateTakeType
	} from '../../common/api/index.js';
	import {
		_showLoading,
		_showToast
	} from '../../common/js/util.js'
	import mcModal from '../../components/custom-modal/mc-modal.vue'
	import noContent from '@/components/no-content.vue'
	export default {
		components: {
			mcModal,
			noContent
		},
		data() {
			return {
				showOrg: false,
				marchrtList: [],
				tabMeal: [{
					title:'食堂报餐',
					index: 1
				},{
					title:'我的报餐',
					index: 2
				},{
					title:'扫码用餐',
					index: 3
				}],
				current: 1,
				tabIndex: 0,
				mealList: [],
				canUseList: [],
				myMeal:[{
					title: '全部',
					status: ''
				},{
					title: '待确定',
					status: 10
				},{
					title: '已预订',
					status: 20
				},{
					title: '已完成',
					status: 30
				},{
					title: '已关闭',
					status: 40
				}],
				zoneCode: '',
				orgId: '',
				empId: '',
				empName: '',
				showMcModal: false,
				title: '',
				content: '',
				showCancel: true,
				openQrcode: false,
				qrcode: 0,
				qrcodeMsg: {},
				timer: null,
				ranges: []
			}
		},
		onLoad(option) {
			_this = this
			_this.current = option.current?option.current:1
		},
		onShow(){
			_this._queryStudentCardBalance()
		},
		methods: {
			mealHandle(e) {
				this.current = e.index
				if(e.index == 1) _this._getMarchrtList()
				else if(e.index == 2) _this.tabChange({index: _this.tabIndex})
				else if(e.index == 3) _this._getMealOrder()
			},
			// 选择我的预定订单类型
			tabChange(e) {
				this.tabIndex = e.index
				this.mealPage = 1
				this.mealList = []
				this._getMealOrderPage(this.myMeal[e.index].status)
			},
			// 商家数据加载
			_getMarchrtList() {
				_showLoading('数据加载中...')
				let obj = {
					orgId: _this.orgId,
					zoneCode: _this.zoneCode,
					page: 1,
					limit: 300
				}
				getMerchantList(obj).then(res => {
					uni.hideLoading()
					if (res.resultCode == 0) {
						_this.marchrtList = res.data.list.map(e => {
							e.icon = 'https://sndcard.com//app_image_file/' + e.icon;
							return e
						})
					} else {
						_showToast('数据请求异常：' + res.resultMsg)
					}
				}).catch(err => {
					uni.hideLoading()
					console.log(err)
				})
			},
			// 我预定的餐食数据
			_getMealOrderPage(status) {
				_showLoading('数据加载中...')
				findMealOrderPage({
					page: 1,
					limit: 50,
					empId: _this.empId,
					status: status,
				}).then(res => {
					uni.hideLoading()
					if (res.code == 0) {
						if (res.data.list.length > 0) {
							_this.mealList = _this.mealList.concat(res.data.list)
						}
					} else {
						_showToast('请求异常！')
					}
				}).catch(err => {
					uni.hideLoading()
					_showToast('请求异常！')
				})
			},
			//我预定的可用餐数据
			_getMealOrder(){
				_showLoading('数据加载中...')
				 findMealOrder({
					empId: _this.empId,
					orgId: _this.orgId,
				}).then(res => {
					uni.hideLoading()
					if(res.resultCode == 0) {
						if (res.data) {
							_this.canUseList = res.data
						}else{
							_this.canUseList = []
						}
					} else {
						_showToast('请求异常！'+res.resultMsg)
					}
				}).catch(err => {
					uni.hideLoading()
					console.log(err)
				})
			},
			// 可选机构加载
			_queryStudentCardBalance(orgId) {
				uni.showLoading({
					mask: true,
					title: '加载中...'
				})
				let s_userId = uni.getStorageSync('s_userId')
				queryStudentCardBalance({
					userId: s_userId,
					orgId: orgId?orgId:null,
					queryCard: true,
					queryWallet: true,
					// bindType: 0
				}).then(res => {
					if (res.code == 0) {
						let students = res.data.students,orgs = res.data.orgs
						let lv1 = [],lv2 = [];
						
						uni.hideLoading()
						orgs.forEach(item => {
							item.value = item.orgId
							item.txt = item.orgName
							lv1.push(item)
						})
						students.forEach(item => {
							let stu = item.students[0]
							stu.value = stu.orgId
							stu.txt = stu.empName
							lv2.push(stu)
						})
						_this.ranges = [lv1, lv2]
						if(!orgId){
							_this._confirmStudent([lv1[0],lv2[0]])
						}
						
					} else {
						uni.hideLoading()
						_this.ranges = []
					}
				}).catch(err => {
					uni.hideLoading()
					console.log(err)
				})
			},
			// 选择机构
			_SchoolsChange(data) {
				if(data[0].value == _this.orgId) return
				_this.orgId = data[0].value
				_this._queryStudentCardBalance(data[0].value)
			},
			//确认用户
			_confirmStudent(data){
				uni.setNavigationBarTitle({
					title: `${data[1].orgName}:${data[1].empName}`
				}) 
				// uni.showToast({
				// 	icon: 'none',
				// 	title: `切换${data[1].orgName}:${data[1].empName}用户成功！！！`,
				// 	duration: 3000
				// })
				
				// _this.showCancel = false,
				// _this.showMcModal = true,
				// _this.title = '提示',
				// _this.content = `当前选择的用户为：${data[1].empName}(${data[1].orgName})`,
				// _this.ok = () => {
				// 	_this.showMcModal = false
				// 	_this.showCancel = true
				// }
				_this.zoneCode = data[1].zoneCode;
				_this.orgId = data[1].orgId;
				_this.empId = data[1].empId;
				_this.empName = data[1].empName;
				_this._getMarchrtList()
				_this.tabChange({index: 0})
			},
			//点击商家
			_changeMarchrt(marchrt){
				uni.navigateTo({
					url: `./mealFood?marchrt=${encodeURIComponent(JSON.stringify(marchrt))}&userinfo=${encodeURIComponent(JSON.stringify({zoneCode: _this.zoneCode,orgId: _this.orgId,empId: _this.empId,empName: _this.empName}))}`
				})
			},
			//确认预约订单
			confirmOrder(item, canDo){
				item = {...item,orderNo: item.orderNo,time: item.reservationDate,orgId: _this.orgId,...item.odtsDeviceFamilyEntity,canDo: item.status == 10}
				uni.navigateTo({
					url: `./mealConfirm?supply=${encodeURIComponent(JSON.stringify(item))}`
				})
			},
			// 确认退订订单
			cancelOrderHandle(item){
				_this.showMcModal = true,
				_this.title = '确认退订吗？',
				_this.content = '退订之后想再次预订，可以到商家供应列表再次预订！',
				_this.ok = _this._cancelOrder(item)
			},
			// 退订订单
			_cancelOrder(item){
				return function(){
					_this.showMcModal = false
					_showLoading('退订中...')
					let obj = {
						orderNo: item.orderNo,
						orgId: _this.orgId,
						closeType: 20
					}
					cancelMealOrder(obj).then(res => {
						uni.hideLoading()
						if(res.resultCode == 0) {
							_showToast('退订成功~欢迎再次预订！')
							setTimeout(()=>{_this.tabChange({index: _this.tabIndex})},1000)
						} else {
							_showToast(res.resultMsg)
						}
					}).catch(err => {
						uni.hideLoading()
						console.log(err)
					})
				}
			},
			// 删除订单
			orderInvisible(item){
				orderToInvisible({
					orderNo: item.orderNo,
					orgId: item.orgId
				}).then(res => {
					if(res.code == 0) {
						_showToast('删除成功')
						setTimeout(()=>{_this.tabChange({index: _this.tabIndex})},1000)
					} else {
						_showToast('删除成功')
					}
				}).catch(err => {
					console.log(err)
				})
			},
			// 展示二维码
			showQrcode(item){
				this.openQrcode = true
				this.qrcode = item.orderNo
				this.qrcodeMsg = item
				// this.$refs.qrcode._makeCode()
				this._updateTakeType()
			},
			// 隐藏(关闭)二维码
			hideQrcode(){
				this.openQrcode = false
				clearInterval(_this.timer);
				_this.timer = null;
			},
			// 获取二维码状态
			_updateTakeType(){
				_this.timer = setInterval(() => {
					updateTakeType({
						orderNo: _this.qrcodeMsg.orderNo,
						empId: _this.empId,
						orgId: _this.orgId
					}).then(res => {
						if(res.data == 1) {
							_this.showCancel = false,
							_this.showMcModal = true,
							_this.title = '操作提示',
							_this.content = '报餐取餐成功~',
							_this.ok = () => {
								_this.showMcModal = false
								_this.showCancel = true,
								_this.hideQrcode()
								_this._getMealOrder()
							}
						}
					}).catch(err => {
						this.$vux.loading.hide()
						console.log(err)
					})
				}, 1500)
			},
			imgLoad(e) {
				console.log(e)
			},
			imgError(e) {
				console.log(e)
			},
			ok() {}
		},
		
		computed:{
			statusToType(status) {
				return function(status) {
					if(status == 10) {
						return '待确认'
					} else if(status == 20) {
						return '已预约'
					} else if(status == 21) {
						return '已用餐'
					}else if(status == 22) {
						return '部分支付'
					}else if(status == 30) {
						return '已结算'
					}else if(status == 40) {
						return '已关闭'
					}else if(status == 50) {
						return '订单完成'
					}else if(status == 60) {
						return '订单已关闭'
					}
				}
			}	
		}
	}
</script>

<style lang="scss">
	page{
		height: 100%;
		width: 100%;
	}
	.content {
		height: 100%;
		background-color: #F8F8F8;
	}

	.container {
		height: 100%;
		// position: relative;
		padding-bottom: 100rpx;
		box-sizing: border-box;
		overflow-y: auto;
	}

	.tab_meal {
		height: 100rpx;
		width: 100%;
		position: fixed;
		bottom: 0;
		z-index: 99;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
		background-color: #FFF;

		.tab_item {
			text-align: center;
			line-height: 100rpx;
			color: #666;

			&.current {
				color: #185AFF;
				font-weight: 700;
			}
		}
	}

	.marchrt_box {
		padding: 24rpx;
	}

	.marchrt {
		margin-bottom: 24rpx;
	}

	.marchrt_main {
		display: flex;
		justify-content: flex-start;
		flex-direction: row;
		align-items: center;

		.marchrt_header {
			margin-right: 36rpx;

			.marchrt_header_img {
				width: 160rpx;
				height: 160rpx;
			}
		}

		.marchrt_content {
			.marchrt_name {
				font-size: 32rpx;
				font-weight: 600;
				color: #3C424F;
				line-height: 44rpx;
			}

			.marchrt_remark {
				font-size: 28rpx;
				font-weight: 600;
				color: #6B707A;
				line-height: 40rpx;
				padding: 20rpx 0 30rpx;
			}

			.marchrt_start_and {
				font-size: 24rpx;
				font-weight: 500;
				color: #9AA2B2;
				line-height: 34rpx;
			}
		}
	}

	.org_change {
		position: fixed;
		width: 120rpx;
		right: 20rpx;
		bottom: 120rpx;
		color: #FFF;
		background-color: #007AFF;
		box-shadow: 0 8rpx 16rpx 0 rgba(0, 0, 0, 0.28);
		border-radius: 40rpx;
		padding: 8rpx 20rpx;
		font-size: 24rpx;

		// .org_name{
		// 	text-align: center;
		// 	padding: 12rpx;
		// }
		.change_btn {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: row;

			.change_icon {
				width: 56rpx;
				height: 56rpx;
				flex: none;
			}
		}
	}
	.tab_my_meal{
		position: absolute;
		top: 0;
		width: 100%;
		z-index: 99;
	}
	.my_meal_list{
		box-sizing: border-box;
		overflow-y: auto;
		padding: 132rpx 32rpx 32rpx;
	}
	.supply_item{
		margin-bottom: 20rpx;
	}
	.supply_header{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		position: relative;
		
		&::before{
			content: "";
			display: block;
			position: absolute;
			width: 10rpx;
			height: 10rpx;
			border-radius: 50%;
			background-color: #185AFF;
			left: -16rpx;
		}
		.supply_type{
			font-size: 32rpx;
			font-weight: 600;
			color: #3C424F;
			line-height: 44rpx;
		}
		.supply_result{
			display: flex;
			flex-direction: row;
			align-items: center;
			font-size: 28rpx;
			font-weight: 500;
			color: #FA6400;
			line-height: 40rpx;
		}
		.result_icon{
			width: 36rpx;
			height: 36rpx;
			margin-right: 12rpx;
		}
		.supply_result.agree{
			color: #55C976;
		}
		.supply_result.not_agree{
			color: #E02020;
		}
		.supply_result.appling{
			color: #FA6400;
		}
	}
	.supply_description{
		font-size: 32rpx;
		font-weight: 600;
		color: #6B707A;
		line-height: 40rpx;
		padding: 20rpx 0 10rpx 0;
	}
	.supply_menus{
		padding: 20rpx 0;
		.menu_item{
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			line-height: 48rpx;
			font-size: 28rpx;
			color: #999;
		}
	}
	.supply_price{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 0;
		font-size: 22rpx;
		font-weight: 500;
		color: #9AA2B2;
		line-height: 34rpx;
		.hint{
			font-size: 30rpx;
			color: #FA6400;
		}
		.status_btn_box{
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}
		.book_btn{
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			height: 48rpx;
			padding: 0 16rpx;
			margin: 0 6rpx;
			background-color: #007AFF;
			color: #FFF;
			border-radius: 48rpx;
			.icon {
				width: 30rpx;
				height: 30rpx;
			}
		}
	}
	.meal_qrcode{
		// height: calc(100vh - 100rpx);
		padding: 132rpx 32rpx 32rpx;
		padding: 36rpx;
		box-sizing: border-box;
		overflow-y: auto;
	}
	.show_qrcode{
		text-align: center;
		color: #007AFF;
		font-weight: 700;
		padding-top: 24rpx;
	}
	.qr_code_box{
		width: 100vw;
		height: 100vh;
		position: fixed;
		top: 0;
		left: 0;
		.mask{
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.2);
			z-index: 99;
		}
		.qr_code_bg{
			z-index: 996;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			background-color: #FFF;
			width: 90%;
			position: absolute;
			top: 50%;
			left: 50%;
			padding: 24rpx;
			border-radius: 12rpx;
			transform: translate(-50%, -50%);
			box-sizing: border-box;
		}
		.qr_code_msg{
			padding: 48rpx;
			.msg_item{
				line-height: 60rpx;
				font-size: 32rpx;
				.msg_title{
					color: #999;
					margin-right: 24rpx;
				}
				.msg_content{
					color: #333;
				}
			}
		}
		.qr_code_merchant{
			font-size: 36rpx;
			font-weight: 700;
			padding: 48rpx 0;
		}
		.close_icon{
			font-size: 64rpx;
			position: absolute;
			top: 16rpx;
			right: 16rpx;
			width: 64rpx;
			height: 64rpx;
			text-align: center;
			line-height: 56rpx;
			color: #999;
		}
	}
	.no_data{
		padding: 100rpx 0;
	}
</style>
